package com.ruicar.afs.cloud.apply.pre.loan.mq.sender.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.aggregate.aggregateport.AggregateApiFeign;
import com.ruicar.afs.cloud.aggregate.dto.AffiliatedCheckDto;
import com.ruicar.afs.cloud.aggregate.dto.CertNoCheckDto;
import com.ruicar.afs.cloud.aggregate.dto.CertNoDto;
import com.ruicar.afs.cloud.aggregate.dto.UsedVinInfoDto;
import com.ruicar.afs.cloud.apply.business.service.ApplyRecordDetailsService;
import com.ruicar.afs.cloud.apply.business.service.TSysParamConfigService;
import com.ruicar.afs.cloud.apply.business.service.WorkflowAgencyTaskService;
import com.ruicar.afs.cloud.apply.channel.feign.ApplyUseChannelFeign;
import com.ruicar.afs.cloud.apply.common.dto.ChannelAffiliatedUnitsDto;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.feign.Apply2ChannelFeign;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConfig;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.pre.loan.condition.CaseSubmitInfoCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ContractCancelCondition;
import com.ruicar.afs.cloud.apply.pre.loan.mq.dto.CaseSbmitInfoDto;
import com.ruicar.afs.cloud.apply.pre.loan.mq.sender.service.CaseSubmitInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.service.impl.ApplyOrderInfoServiceImpl;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinDiscountDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinRentAdjustDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyDiscountDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyFinancingItemsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyRentAdjustDetailsService;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.AffiliatedWayEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessTypeEnum;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.*;
import com.ruicar.afs.cloud.common.modules.enums.ApplySceneEnum;
import com.ruicar.afs.cloud.common.modules.enums.OprTypeEnum;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleDetail;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleModel;
import com.ruicar.afs.cloud.parameter.commom.enums.*;
import com.ruicar.afs.cloud.parameter.commom.service.TsysVehicleDetailService;
import com.ruicar.afs.cloud.parameter.commom.service.TsysVehicleModelService;
import com.ruicar.afs.cloud.vehicle.dto.CarInfoDto;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 进件申请提交案件审批实现类
 *
 * @author 耿继辉
 */
@Service
@Slf4j
@AllArgsConstructor
public class CaseSubmitInfoServiceImpl implements CaseSubmitInfoService {
    private final ApplyCustAddressService applyCustAddressService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ApplyCustContactsService applyCustContactsService;
    private final ApplyCustPersonalService applyCustPersonalService;
    private final ApplyAffiliatedUnitService applyAffiliatedUnitService;
    private final ApplyCarDetailsService applyCarDetailsService;
    private final ApplyCostDetailsService applyCostDetailsService;
    private final ApplyDiscountDetailsService applyDiscountDetailsService;
    private final ApplyFinancingItemsService applyFinancingItemsService;
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ApplyOrderInfoServiceImpl orderInfoService;
    private final TsysVehicleDetailService tsysVehicleDetailService;
    private final TsysVehicleModelService tsysVehicleModelService;
    private final ApplyChannelInfoService applyChannelInfoService;
    private final ApplyRecordDetailsService applyRecordDetailsService;
    private final ApplyRentAdjustDetailsService applyRentAdjustDetailsService;
    private final ApplyModifyHistoryService applyModifyHistoryService;
    private final ApplyOprRecordService applyOprRecordService;
    private final ComAttachmentFileService comAttachmentFileService;
    private final AggregateApiFeign aggregateApiFeign;
    private final ApplyConfig config;
    private final WorkflowAgencyTaskService workflowAgencyTaskService;
    private final TSysParamConfigService sysParamConfigService;
    private final ApplyUseChannelFeign applyUseChannelFeign;
    private final ApplyRemindDetailsService applyRemindDetailsService;
    private final TSysParamConfigService tSysParamConfigService;
    private final Apply2ChannelFeign apply2ChannelFeign;

    /**
     * 进件提交报文组装
     *
     * @param applyNo
     * @return
     */
    @Override
    public AfsTransEntity<OrderSubmitInfo> returnMessage(String applyNo) throws ParseException {
        AfsTransEntity<OrderSubmitInfo> transEntity = new AfsTransEntity();
        //查询挂靠信息
        ApplyAffiliatedUnit affiliatedUnitByApplyNo = this.applyAffiliatedUnitService.getAffiliatedUnitByApplyNo(applyNo);
        if (ObjectUtil.isNotNull(affiliatedUnitByApplyNo)) {
            //如果挂靠类型为第三方挂靠
            if (AffiliatedWayEnum.COMPANY_AFFILIATED.getCode().equals(affiliatedUnitByApplyNo.getAffiliatedType())) {
                if (StringUtil.isNotEmpty(affiliatedUnitByApplyNo.getAffiliatedId())) {
                    Map<String, String> headers = new HashMap<>();
                    headers.put("clientId", config.getChannelClientId());
                    headers.put("clientSecret", config.getChannelClientSecret());
                    this.applyUseChannelFeign.affiliatedCount(String.valueOf(affiliatedUnitByApplyNo.getAffiliatedId()), headers);
                }
            }
        }
        CaseSbmitInfoDto checkData = this.checkData(applyNo);
        OrderSubmitInfo orderSubmitInfo = this.orderSubmitInfoAssemble(checkData, applyNo);
        //查询审批记录
        List<WorkflowRecordDetails> recordDetailsList = applyRecordDetailsService.list(Wrappers.<WorkflowRecordDetails>query().lambda().eq(WorkflowRecordDetails::getBusinessNo, applyNo));
        //查询操作记录为复议的数据
        List<ApplyOprRecord> applyOprRecordList = this.applyOprRecordService.list(Wrappers.<ApplyOprRecord>query()
                .lambda().eq(StringUtil.isNotEmpty(applyNo), ApplyOprRecord::getApplyNo, applyNo)
                .eq(ApplyOprRecord::getApplyType, String.valueOf(OrderOprType.RECONSIDER)));
        List<ApplyRemindDetails> remindDetailsList = applyRemindDetailsService.list(Wrappers.<ApplyRemindDetails>query().lambda()
                .eq(StringUtil.isNotEmpty(applyNo), ApplyRemindDetails::getApplyNo, applyNo)
                .eq(ApplyRemindDetails::getRemindType, AProveBusinessTypeEnum.SEND_BACK_TO_DEALER.getCode()));
        //订单草稿状态
        if (ApplyConstants.APPLY_STATUS_DRAFT.equals(checkData.getApplyOrderInfo().getApplyStatus())
                || ApplyConstants.CALL_BACK_WAIT_SUBMIT.equals(checkData.getApplyOrderInfo().getApplyStatus())
                || ApplyConstants.APPLY_STATUS_REVIEWPENDINGSUBMISSION.equals(checkData.getApplyOrderInfo().getApplyStatus())) {
            //查找操作记录是否含有撤回记录
            ApplyOprRecord callBackOprRecord = applyOprRecordService.getOne(Wrappers.<ApplyOprRecord>query()
                    .lambda().eq(StringUtil.isNotEmpty(applyNo), ApplyOprRecord::getApplyNo, applyNo)
                    .eq(ApplyOprRecord::getApplyType, OrderOprType.BACK));
            //没有审批记录,留言为空,首次提交
            if (CollectionUtil.isEmpty(recordDetailsList) && CollectionUtil.isEmpty(remindDetailsList)) {
                //常规审批，首次提交，新增
                orderSubmitInfo.setApplyScene(ApplySceneEnum.GENERALAPPROVAL.getCode());
                //如果有撤回操作，则是修改订单
                if (ObjectUtil.isNotNull(callBackOprRecord)) {
                    orderSubmitInfo.setOprType(OprTypeEnum.OPRUPDATE.getCode());
                    //更新订单状态为已提交
                    checkData.getApplyOrderInfo().setApplyStatus(ApplyConstants.APPLY_STATUS_SUBMIT);
                    checkData.getApplyOrderInfo().setApplyReporter(checkData.getApplyOrderInfo().getCreateBy());
                    checkData.getApplyOrderInfo().setApplyNo(applyNo);
                    this.orderInfoService.updateOrderApplyStatus(checkData.getApplyOrderInfo());
                    //退回后提交修改文件历史版本
                    this.comAttachmentFileService.updateFileVersionByBusiNo(applyNo, "orderApply");
                    log.info("撤回后重新提交：{}", applyNo);
                } else {
                    orderSubmitInfo.setOprType(OprTypeEnum.OPRADD.getCode());
                    //更新订单状态为已提交
                    checkData.getApplyOrderInfo().setApplyStatus(ApplyConstants.APPLY_STATUS_SUBMIT);
                    checkData.getApplyOrderInfo().setApplyReporter(checkData.getApplyOrderInfo().getCreateBy());
                    checkData.getApplyOrderInfo().setIntoFirstDate(new Date());
                    checkData.getApplyOrderInfo().setApplyNo(applyNo);
                    this.orderInfoService.updateOrderApplyStatus(checkData.getApplyOrderInfo());
                    /**首次提交修改状态*/
                    this.comAttachmentFileService.updateFileStatusByBusiNo(applyNo);
                    log.info("订单首次提交：{}", applyNo);
                }
            } else if (CollectionUtil.isNotEmpty(remindDetailsList)) {
                //留言不为空
                remindDetailsList.forEach(applyRemindDetails -> {
                    //如果是流程外退回->提交，更新订单状态为已提交，场景常规审批,修改
                    if (AProveBusinessTypeEnum.SEND_BACK_TO_DEALER.getCode().equals(applyRemindDetails.getRemindType())) {
                        //复议流程外退回
                        if (String.valueOf(OrderOprType.RECONSIDER).equals(applyRemindDetails.getBusinessType())) {
                            orderSubmitInfo.setOprType(OprTypeEnum.OPRUPDATE.getCode());
                            orderSubmitInfo.setApplyScene(ApplySceneEnum.FORMALREVIEW.getCode());
                            //修改订单为已提交
                            this.orderInfoService.updateApplyStatus(applyNo, ApplyConstants.APPLY_STATUS_PENDING);
                        } else {
                            //常规流程退回
                            orderSubmitInfo.setOprType(OprTypeEnum.OPRUPDATE.getCode());
                            orderSubmitInfo.setApplyScene(ApplySceneEnum.GENERALAPPROVAL.getCode());
                            //修改订单为已提交
                            this.orderInfoService.updateApplyStatus(applyNo, ApplyConstants.APPLY_STATUS_SUBMIT);
                        }
                        log.info("流程外退回订单重新提交：{}", applyNo);
                    }
                });
            } else if (CollectionUtil.isNotEmpty(applyOprRecordList)) {
                //存在复议信息,复议
                //更新订单状态为待审核
                this.orderInfoService.updateApplyStatus(applyNo, ApplyConstants.APPLY_STATUS_PENDING);
                //正式复议,场景正式，修改
                orderSubmitInfo.setApplyScene(ApplySceneEnum.FORMALREVIEW.getCode());
                orderSubmitInfo.setOprType(OprTypeEnum.OPRUPDATE.getCode());
                log.info("正式复议提交：{}", applyNo);
            } else if (CollectionUtil.isNotEmpty(recordDetailsList)) {
                //流程内撤回后重新提交
                if (ObjectUtil.isNotNull(callBackOprRecord)) {
                    //常规审批
                    if (ApplyConstants.CALL_BACK_WAIT_SUBMIT.equals(checkData.getApplyOrderInfo().getApplyStatus())) {
                        orderSubmitInfo.setIsCallBackSubmit(com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum.YES.getCode());
                    }
                    orderSubmitInfo.setApplyScene(ApplySceneEnum.GENERALAPPROVAL.getCode());
                    orderSubmitInfo.setOprType(OprTypeEnum.OPRUPDATE.getCode());
                    //更新订单状态为已提交
                    checkData.getApplyOrderInfo().setApplyStatus(ApplyConstants.APPLY_STATUS_SUBMIT);
                    checkData.getApplyOrderInfo().setApplyReporter(checkData.getApplyOrderInfo().getCreateBy());
                    checkData.getApplyOrderInfo().setApplyNo(applyNo);
                    this.orderInfoService.updateOrderApplyStatus(checkData.getApplyOrderInfo());
                    log.info("撤回后重新提交：{}", applyNo);
                }
            }
        } else if (ApplyConstants.APPLY_STATUS_SUSPEND.equals(checkData.getApplyOrderInfo().getApplyStatus())) {
            //待办任务内有复议退回,就是正式复议的退回
            //查询待办任务
            WorkflowAgencyTask agencyTaskServiceOne = this.workflowAgencyTaskService.getOne(Wrappers.<WorkflowAgencyTask>query()
                    .lambda().eq(WorkflowAgencyTask::getBusinessNo, applyNo));
            if (ObjectUtil.isNotNull(agencyTaskServiceOne)) {
                //查审批记录
                List<WorkflowRecordDetails> workflowRecordDetailsList = this.applyRecordDetailsService.list(Wrappers.<WorkflowRecordDetails>query().lambda()
                        .eq(WorkflowRecordDetails::getBusinessNo, applyNo).eq(WorkflowRecordDetails::getApproveResult, AProveBusinessTypeEnum.BACK.getCode())
                        .eq(WorkflowRecordDetails::getProcessId, agencyTaskServiceOne.getProcessId()));
                //如果是复议退回
                if (String.valueOf(OrderOprType.RECONSIDER).equals(agencyTaskServiceOne.getBusinessType())) {
                    //退回的审批记录
                    recordDetailsList.forEach(workflowRecordDetails -> {
                        if (AProveBusinessTypeEnum.BACK.getCode().equals(workflowRecordDetails.getApproveResult())) {
                            if (ObjectUtil.isNotNull(workflowRecordDetails)) {
                                orderSubmitInfo.setDataId(workflowRecordDetails.getProcessId());
                            }
                            this.orderInfoService.updateApplyStatus(applyNo, ApplyConstants.APPLY_STATUS_REPLY);
                            orderSubmitInfo.setLeaveMessage(assemblyData(applyNo).toString());
                            orderSubmitInfo.setApplyScene(ApplySceneEnum.FORMALREVIEW.getCode());
                            //复议退回修改
                            orderSubmitInfo.setOprType(OprTypeEnum.UPDATE_RECONSIDER.getCode());
                            //移除代办任务
                            this.workflowAgencyTaskService.removeById(agencyTaskServiceOne);
                            log.info("复议退回订单提交：{}", applyNo);
                        }
                    });
                } else if (String.valueOf(OrderOprType.NORMAL).equals(agencyTaskServiceOne.getBusinessType())) {
                    //进件退回,常规审批,修改
                    orderSubmitInfo.setApplyScene(ApplySceneEnum.GENERALAPPROVAL.getCode());
                    orderSubmitInfo.setOprType(OprTypeEnum.OPRUPDATE.getCode());
                    if (CollectionUtil.isNotEmpty(workflowRecordDetailsList)) {
                        orderSubmitInfo.setDataId(workflowRecordDetailsList.get((workflowRecordDetailsList.size() - 1)).getProcessId());
                    }
                    //退回(修订暂停)->提交信审->修订回复
                    this.orderInfoService.updateApplyStatus(applyNo, ApplyConstants.APPLY_STATUS_REPLY);
                    orderSubmitInfo.setLeaveMessage(assemblyData(applyNo).toString());
                    //移除代办任务
                    this.workflowAgencyTaskService.removeById(agencyTaskServiceOne);
                    //退回后-提交修改文件历史版本
                    this.comAttachmentFileService.updateFileVersionByBusiNo(applyNo, "orderApply");
                    log.info("进退回后-提交修改文件历史版本：{}", applyNo);
                    //影像件信息
                    List<ComAttachmentFile> comAttachmentFileList = this.comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                            .eq(StringUtil.isNotEmpty(applyNo), ComAttachmentFile::getBusiNo, applyNo));
                    //影像件
                    ArrayList<ComAttachmentFileDto> attachmentFileDtoArrayList = this.comAttachmentFile(comAttachmentFileList);
                    orderSubmitInfo.setComAttachmentFileListDto(attachmentFileDtoArrayList);
                    log.info("进件订单退回（文件历史版本更新）：{}", applyNo);
                    log.info("进件订单退回（修订暂停->修订回复）：{}", applyNo);
                }
            }
        } else if (checkData.getApplyOrderInfo().getApplyStatus().equals(ApplyConstants.APPLY_STATUS_REVOKE)) {
            //撤销的订单不可再次提交
            throw new AfsBaseException("申请编号为:" + checkData.getApplyOrderInfo().getApplyNo() + "的订单已撤销,不可重复提交");
        }
        transEntity.setTransCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_NEW_ORDER);
        transEntity.setData(orderSubmitInfo);
        return transEntity;
    }

    /**
     * 数据组装
     *
     * @param checkData
     * @return
     */
    public OrderSubmitInfo orderSubmitInfoAssemble(CaseSbmitInfoDto checkData, String applyNo) {
        OrderSubmitInfo orderSubmitInfo = new OrderSubmitInfo();
        //案件-客户个人明细list
        ArrayList<CaseCustIndividualDto> caseCustIndividualList = this.caseCustIndividualList(checkData.getApplyCustBaseInfoList());
        //案件-客户基础信息list
        ArrayList<CaseCustInfoDto> caseCustInfoList = this.caseCustBaseInfo(checkData.getApplyCustBaseInfoList());
        //案件-客户地址明细list
        ArrayList<CaseCustAddressDto> caseCustAddressDtos = this.caseCustAddressList(checkData.getAddressDetailsList());
        //案件-客户联系人明细list
        ArrayList<CaseCustContactDto> caseCustContactDtos = this.caseCustContactList(checkData.getApplyCustContactsList());
        //案件-渠道
        CaseChannelInfoDto caseChannelInfoDto = this.caseChannelInfo(checkData.getApplyChannelInfo(), checkData.getApplyOrderInfo());
        //案件-基本信息
        CaseBaseInfoDto caseBaseInfoDto = this.caseBaseInfoDTO(checkData.getApplyOrderInfo(), checkData.getApplyCustBaseInfoList(), checkData.getFinCostDetailsList());
        //案件-车辆信息
        ArrayList<CaseCarInfoDto> caseCarInfoDtos = this.caseCarInfoList(checkData.getApplyCarDetails(), checkData.getApplyOrderInfo());
        //案件-融资信息
        ArrayList<FinCostDetails> caseCostInfoDtos = this.caseCostInfoList(checkData.getFinCostDetailsList());
        //案件-融资项目信息
        ArrayList<FinFinancingItems> caseFinancingItemList = this.caseFinancingItemList(checkData.getFinancingItemsList());
        //案件-贴息明细
        ArrayList<FinDiscountDetails> caseDiscountDetailList = this.caseDiscountDetailList(checkData.getDiscountDetailsList());
        //案件-车辆样式信息
        ArrayList<CaseCarStyleDetailDto> caseCarStyleDetailList = this.caseCarStyleDetailList(checkData.getApplyCarDetails(), checkData.getTsysVehicleDetail(), checkData.getTsysVehicleModel());
        //租金调整
        ArrayList<FinRentAdjustDetails> adjustDetailsDtoArrayList = this.applyRentAdjustDetails(checkData.getRentAdjustDetailsList());
        //影像件
        ArrayList<ComAttachmentFileDto> attachmentFileDtoArrayList = this.comAttachmentFile(checkData.getAttachmentFileList());
        orderSubmitInfo.setCaseCustIndividualList(caseCustIndividualList);
        orderSubmitInfo.setCaseCustInfoList(caseCustInfoList);
        orderSubmitInfo.setCaseCustAddressList(caseCustAddressDtos);
        orderSubmitInfo.setCaesCustContactList(caseCustContactDtos);
        orderSubmitInfo.setCaseChannelInfo(caseChannelInfoDto);
        orderSubmitInfo.setCaseBaseInfo(caseBaseInfoDto);
        orderSubmitInfo.setCaseCarInfoList(caseCarInfoDtos);
        orderSubmitInfo.setCaseCostInfoList(caseCostInfoDtos);
        orderSubmitInfo.setCaseFinancingItemList(caseFinancingItemList);
        orderSubmitInfo.setCaseDiscountDetailList(caseDiscountDetailList);
        orderSubmitInfo.setCaseCarStyleDetailList(caseCarStyleDetailList);
        orderSubmitInfo.setApplyRentAdjustDetailsList(adjustDetailsDtoArrayList);
        orderSubmitInfo.setComAttachmentFileListDto(attachmentFileDtoArrayList);
        orderSubmitInfo.setApplyNo(applyNo);
        return orderSubmitInfo;
    }

    /**
     * 获取退回订单-进件留言
     *
     * @param applyNo
     * @return
     */
    @Override
    public StringBuilder assemblyData(String applyNo) {
        StringBuilder message = new StringBuilder();
        //查询修订回复留言
        List<ApplyRemindDetails> detailsList = this.applyRemindDetailsService.list(Wrappers.<ApplyRemindDetails>query().lambda().eq(ApplyRemindDetails::getApplyNo, applyNo));
        if (CollectionUtil.isNotEmpty(detailsList)) {
            for (ApplyRemindDetails applyRemindDetails : detailsList) {
                //进件留言,且未发送至审批
                if (WhetherEnum.YES.getIndex().equals(applyRemindDetails.getIsSelf()) && StringUtil.isEmpty(applyRemindDetails.getRemindType())) {
                    if (StringUtil.isEmpty(applyRemindDetails.getIsReturn())) {
                        applyRemindDetails.setIsReturn(com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum.NO.getCode());
                        applyRemindDetailsService.updateById(applyRemindDetails);
                        message = message.append(applyRemindDetails.getMsgContent()).append(",");
                    }
                }
            }
            log.info("进件订单退回（修订暂停->修订回复）：{},进件留言组装", applyNo);
        }
        return message;
    }

    /**
     * 案件需要的客户基础信息list
     *
     * @param applyCustBaseInfoList
     * @return
     */
    @Override
    public ArrayList<CaseCustInfoDto> caseCustBaseInfo(List<ApplyCustBaseInfo> applyCustBaseInfoList) {
        ArrayList<CaseCustInfoDto> caseCustInfoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(applyCustBaseInfoList)) {
            for (ApplyCustBaseInfo applyCustBaseInfo : applyCustBaseInfoList) {
                CaseCustInfoDto custBaseInfo = new CaseCustInfoDto();
                if (ObjectUtil.isNull(applyCustBaseInfo) || StringUtil.isEmpty(applyCustBaseInfo.getApplyNo())) {
                    throw new AfsBaseException("客户基本信息不存在或申请编号不存在--客户基础信息");
                }
                custBaseInfo.setId(applyCustBaseInfo.getId());
                custBaseInfo.setApplyNo(applyCustBaseInfo.getApplyNo());
                custBaseInfo.setCertNo(applyCustBaseInfo.getCertNo());
                custBaseInfo.setCertType(applyCustBaseInfo.getCertType());
                custBaseInfo.setCustName(applyCustBaseInfo.getCustName());
                custBaseInfo.setCustRelation(applyCustBaseInfo.getCustRelation());
                custBaseInfo.setCustRole(applyCustBaseInfo.getCustRole());
                custBaseInfo.setCustType(applyCustBaseInfo.getCustType());
                custBaseInfo.setCertStartDate(applyCustBaseInfo.getCertStartDate());
                custBaseInfo.setCertEndDate(applyCustBaseInfo.getCertEndDate());
                custBaseInfo.setTelPhone(applyCustBaseInfo.getTelPhone());
                if (Boolean.TRUE.equals(applyCustBaseInfo.getIsLongTerm())) {
                    custBaseInfo.setIsLongTerm(com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum.YES.getCode());
                } else if (Boolean.FALSE.equals(applyCustBaseInfo.getIsLongTerm())) {
                    custBaseInfo.setIsLongTerm(com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum.NO.getCode());
                }
                caseCustInfoList.add(custBaseInfo);
            }
        }
        return caseCustInfoList;
    }

    /**
     * 案件需要的个人客户信息明细
     *
     * @param applyCustBaseInfoList
     * @return
     */
    @Override
    public ArrayList<CaseCustIndividualDto> caseCustIndividualList(List<ApplyCustBaseInfo> applyCustBaseInfoList) {
        ArrayList<CaseCustIndividualDto> caseCustIndividualList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(applyCustBaseInfoList)) {
            for (ApplyCustBaseInfo applyCustBaseInfo : applyCustBaseInfoList) {
                CaseCustIndividualDto caseCustIndividualDTO = new CaseCustIndividualDto();
                //获取个人明细信息,根据客户主表id
                ApplyCustPersonalDetail applyCustPersonalDetail = this.applyCustPersonalService.getOne(Wrappers.<ApplyCustPersonalDetail>query().lambda()
                        .eq(ApplyCustPersonalDetail::getCustId, applyCustBaseInfo.getId()));
                if (ObjectUtil.isNull(applyCustPersonalDetail)) {
                    throw new AfsBaseException("个人信息不存在");
                }
                //根据客户编号查询客户关联的地址信息
                List<ApplyCustAddressDetails> applyCustAddressDetailsList = this.applyCustAddressService.list(Wrappers.<ApplyCustAddressDetails>query().lambda()
                        .eq(ApplyCustAddressDetails::getCustId, applyCustBaseInfo.getId()));
                if (CollectionUtil.isEmpty(applyCustAddressDetailsList)) {
                    throw new AfsBaseException("地址信息不存在");
                }
                if (applyCustAddressDetailsList.size() <= 1) {
                    throw new AfsBaseException("请添加地址信息");
                }
                ApplyCustAddressDetails applyCustAddressDetails = applyCustAddressDetailsList.get(1);
                if (ObjectUtil.isNull(applyCustPersonalDetail) || StringUtil.isEmpty(String.valueOf(applyCustPersonalDetail.getCustId()))) {
                    throw new AfsBaseException("客户号不能为空");
                }
                caseCustIndividualDTO.setAge(applyCustPersonalDetail.getAge());
                caseCustIndividualDTO.setCustId((applyCustPersonalDetail.getCustId()));
                caseCustIndividualDTO.setSpellName(applyCustPersonalDetail.getSpellName());
                caseCustIndividualDTO.setBirthday(applyCustPersonalDetail.getBirthday());
                caseCustIndividualDTO.setSex(applyCustPersonalDetail.getSex());
                caseCustIndividualDTO.setAge(applyCustPersonalDetail.getAge());
                caseCustIndividualDTO.setFamilyNumbers(applyCustPersonalDetail.getFamilyNumbers());
                caseCustIndividualDTO.setMaritalStatus(applyCustPersonalDetail.getMaritalStatus());
                caseCustIndividualDTO.setWorkAge(applyCustPersonalDetail.getWorkAge());
                caseCustIndividualDTO.setDrivingType(applyCustPersonalDetail.getDrivingType());
                caseCustIndividualDTO.setDrivingLicenceNo(applyCustPersonalDetail.getDrivingLicenceNo());
                caseCustIndividualDTO.setHighestEducation(applyCustPersonalDetail.getHighestEducation());
                caseCustIndividualDTO.setProfessional(applyCustPersonalDetail.getProfessional());
                caseCustIndividualDTO.setProfessionalType(applyCustPersonalDetail.getJobsType());
                caseCustIndividualDTO.setUnitName(applyCustPersonalDetail.getUnitName());
                caseCustIndividualDTO.setUnitType(applyCustPersonalDetail.getUnitNature());
                caseCustIndividualDTO.setIndustryType(applyCustPersonalDetail.getIndustryType());
                caseCustIndividualDTO.setEmployeeType(applyCustPersonalDetail.getEmployeeType());
                caseCustIndividualDTO.setPosition(applyCustPersonalDetail.getPosition());
                caseCustIndividualDTO.setScale(applyCustPersonalDetail.getCompanyScale());
                caseCustIndividualDTO.setUnitTelPhone(applyCustPersonalDetail.getCompanyPhone());
                caseCustIndividualDTO.setWorkStartDate(applyCustPersonalDetail.getWorkStartDate());
                if (applyCustPersonalDetail.getMonthlyIncome() != null) {
                    caseCustIndividualDTO.setMonthlyIncome(applyCustPersonalDetail.getMonthlyIncome());
                }
                if (applyCustPersonalDetail.getOutstandingLoan() != null) {
                    caseCustIndividualDTO.setOutstandingLoan(applyCustPersonalDetail.getOutstandingLoan());
                }
                if (applyCustPersonalDetail.getMonthlyIncome() != null) {
                    caseCustIndividualDTO.setOtherIncome(applyCustPersonalDetail.getTotalIncome());
                }
                if (applyCustPersonalDetail.getMonthlySpend() != null) {
                    caseCustIndividualDTO.setMonthlySpend(applyCustPersonalDetail.getMonthlySpend());
                }
                if (applyCustPersonalDetail.getMonthlyPayment() != null) {
                    caseCustIndividualDTO.setMonthlyPayment(applyCustPersonalDetail.getMonthlyPayment());
                }
                caseCustIndividualDTO.setNationality(applyCustPersonalDetail.getNationality());
                caseCustIndividualDTO.setHouseType(applyCustAddressDetails.getHouseType());
                caseCustIndividualDTO.setHouseArea(applyCustAddressDetails.getHouseArea());
                caseCustIndividualDTO.setHouseStartDate(applyCustAddressDetails.getHouseStartDate());
                caseCustIndividualList.add(caseCustIndividualDTO);
            }
        }
        return caseCustIndividualList;
    }


    /**
     * 案件需要的地址明细信息
     *
     * @param applyCustAddressDetailsList
     * @return
     */
    @Override
    public ArrayList<CaseCustAddressDto> caseCustAddressList
    (List<ApplyCustAddressDetails> applyCustAddressDetailsList) {
        ArrayList<CaseCustAddressDto> custCustAddressList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(applyCustAddressDetailsList)) {
            for (ApplyCustAddressDetails applyCustAddressDetails : applyCustAddressDetailsList) {
                CaseCustAddressDto caseCustAddressDTO = new CaseCustAddressDto();
                if (ObjectUtil.isNull(applyCustAddressDetails) || StringUtil.isEmpty(applyCustAddressDetails.getApplyNo())) {
                    throw new AfsBaseException("客户地址信息不存在或申请编号不存在");
                }
                if (ObjectUtil.isNull(applyCustAddressDetails) || StringUtil.isEmpty(String.valueOf(applyCustAddressDetails.getCustId()))) {
                    throw new AfsBaseException("客户号不能为空");
                }
                caseCustAddressDTO.setApplyNo(applyCustAddressDetails.getApplyNo());
                caseCustAddressDTO.setCustId(applyCustAddressDetails.getCustId());
                caseCustAddressDTO.setHouseType(applyCustAddressDetails.getHouseType());
                caseCustAddressDTO.setAddressType(applyCustAddressDetails.getAddressType());
                caseCustAddressDTO.setHouseArea(applyCustAddressDetails.getHouseArea());
                caseCustAddressDTO.setHouseStartDate(applyCustAddressDetails.getHouseStartDate());
                caseCustAddressDTO.setProvince(applyCustAddressDetails.getProvince());
                caseCustAddressDTO.setCity(applyCustAddressDetails.getCity());
                caseCustAddressDTO.setCounty(applyCustAddressDetails.getCounty());
                caseCustAddressDTO.setStreet(applyCustAddressDetails.getStreet());
                caseCustAddressDTO.setGbCode(applyCustAddressDetails.getGbCode());
                caseCustAddressDTO.setDetailAddress(applyCustAddressDetails.getDetailAddress());
                caseCustAddressDTO.setPostalCode(applyCustAddressDetails.getPostalCode());
                caseCustAddressDTO.setIsDefault(String.valueOf(applyCustAddressDetails.getIsDefault()));
                custCustAddressList.add(caseCustAddressDTO);
            }
        }
        return custCustAddressList;
    }

    /**
     * 案件需要的客户联系人信息明细
     *
     * @param applyCustContactsList
     * @return
     */
    @Override
    public ArrayList<CaseCustContactDto> caseCustContactList(List<ApplyCustContacts> applyCustContactsList) {
        ArrayList<CaseCustContactDto> caseCustContactList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(applyCustContactsList)) {
            for (ApplyCustContacts contacts : applyCustContactsList) {
                //获取客户基本信息
                ApplyCustBaseInfo custBaseInfo = this.applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                        .eq(ApplyCustBaseInfo::getApplyNo, contacts.getApplyNo()).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.PRINCIPAL_BORROWER));
                if (ObjectUtil.isNull(contacts) || StringUtil.isEmpty(contacts.getApplyNo())) {
                    throw new AfsBaseException("联系人信息不存在或申请编号不存在");
                }
                if (ObjectUtil.isNull(custBaseInfo)) {
                    throw new AfsBaseException("客户基础信息不存在");
                }
                CaseCustContactDto caseCustContactDTO = new CaseCustContactDto();
                caseCustContactDTO.setCustId(String.valueOf(custBaseInfo.getId()));
                caseCustContactDTO.setApplyNo(contacts.getApplyNo());
                caseCustContactDTO.setCustRelation(contacts.getCustRelation());
                caseCustContactDTO.setCustName(contacts.getCustName());
                caseCustContactDTO.setTelPhone(contacts.getTelPhone());
                caseCustContactDTO.setCertType(contacts.getCertType());
                caseCustContactDTO.setCertNo(contacts.getCertNo());
                caseCustContactDTO.setId(contacts.getId());
                caseCustContactDTO.setCompanyName(contacts.getCompanyName());
                caseCustContactDTO.setCompanyPhone(contacts.getCompanyPhone());
                if (contacts.getMonthlyIncome() != null) {
                    caseCustContactDTO.setMonthlyIncome(BigDecimal.valueOf(contacts.getMonthlyIncome()));
                }
                caseCustContactDTO.setLivingProvince(contacts.getLivingProvince());
                caseCustContactDTO.setLivingCity(contacts.getLivingCity());
                caseCustContactDTO.setLivingCounty(contacts.getLivingCounty());
                caseCustContactDTO.setLivingStreet(contacts.getLivingStreet());
                caseCustContactDTO.setDetailAddress(contacts.getDetailAddress());
                caseCustContactList.add(caseCustContactDTO);
            }
        }
        return caseCustContactList;
    }

    /**
     * 案件渠道信息
     *
     * @param applyChannelInfo
     * @param orderInfoByApplyNo
     * @return
     */
    @Override
    public CaseChannelInfoDto caseChannelInfo(ApplyChannelInfo applyChannelInfo, ApplyOrderInfo orderInfoByApplyNo) {
        CaseChannelInfoDto caseChannelInfoDTO = new CaseChannelInfoDto();
        if (ObjectUtil.isNotNull(applyChannelInfo)) {
            caseChannelInfoDTO.setDealerNo(applyChannelInfo.getChannelCode());
            caseChannelInfoDTO.setDealerName(applyChannelInfo.getChannelName());
            //直营
            if (StringUtil.isNotEmpty(applyChannelInfo.getDirectCarDealersId())) {
                caseChannelInfoDTO.setCarDealersId(applyChannelInfo.getDirectCarDealersId());
                caseChannelInfoDTO.setCarDealersName(applyChannelInfo.getDirectCarDealersName());
            } else if (StringUtil.isNotEmpty(applyChannelInfo.getOrdinaryCarDealersId())) {
                //普通
                caseChannelInfoDTO.setCarDealersId(applyChannelInfo.getOrdinaryCarDealersId());
                caseChannelInfoDTO.setCarDealersName(applyChannelInfo.getOrdinaryCarDealersName());
            }
        }
        if (StringUtil.isEmpty(orderInfoByApplyNo.getApplyNo())) {
            throw new AfsBaseException("申请编号不存在");
        }
        //车商id

        caseChannelInfoDTO.setApplyNo(orderInfoByApplyNo.getApplyNo());
        caseChannelInfoDTO.setSaleAdvisor(orderInfoByApplyNo.getSellerRealName());
        caseChannelInfoDTO.setSalePhone(orderInfoByApplyNo.getSellerPhone());
        return caseChannelInfoDTO;
    }

    /**
     * 案件需要的案件基本信息
     *
     * @param orderInfoByApplyNo    订单信息
     * @param applyCustBaseInfoList 客户基本信息
     * @param finCostDetailsList    融资信息
     * @return
     */
    @Override
    public CaseBaseInfoDto caseBaseInfoDTO(ApplyOrderInfo orderInfoByApplyNo, List<ApplyCustBaseInfo> applyCustBaseInfoList, List<FinCostDetails> finCostDetailsList) {
        CaseBaseInfoDto caseBaseInfoDTO = new CaseBaseInfoDto();
        caseBaseInfoDTO.setApplyNo(orderInfoByApplyNo.getApplyNo());
        caseBaseInfoDTO.setCarType(orderInfoByApplyNo.getCarType());
        caseBaseInfoDTO.setOperateWay(orderInfoByApplyNo.getOperateWay());
        caseBaseInfoDTO.setCustType(orderInfoByApplyNo.getCustType());
        if (orderInfoByApplyNo.getCarNature().equals(CarNature.PLATE_CAR.getIndex())) {
            caseBaseInfoDTO.setBusinessType(AProveBusinessTypeEnum.PLATE.getCode());
        }
        if (StringUtil.isNotEmpty(orderInfoByApplyNo.getSignFlag())) {
            caseBaseInfoDTO.setAutomaticTag(com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum.YES.getCode());
        } else {
            caseBaseInfoDTO.setAutomaticTag(com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum.NO.getCode());
        }
        if (CollectionUtil.isNotEmpty(applyCustBaseInfoList)) {
            String borrowerCertno = null;
            String coborrowerCertno = null;
            for (ApplyCustBaseInfo baseInfo : applyCustBaseInfoList) {
                if (ApplyConstants.PRINCIPAL_BORROWER.equals(baseInfo.getCustRole())) {
                    borrowerCertno = baseInfo.getCertNo();
                } else if (ApplyConstants.COMMON_BORROWER.equals(baseInfo.getCustRole())) {
                    coborrowerCertno = baseInfo.getCertNo();
                }
            }
            //不是修訂暫停的給歷史纍加貸額
            if (!ApplyConstants.APPLY_STATUS_SUSPEND.equals(orderInfoByApplyNo.getApplyStatus())) {
                BigDecimal loanAmount = BigDecimal.ZERO;
                String flag = sysParamConfigService.getParamValue("aggregate-system", "getLoanhistory", WhetherEnum.No.getIndex());
                if (WhetherEnum.YES.getIndex().equals(flag)) {
                    JSONObject json = aggregateApiFeign.getLoanhistory(borrowerCertno, coborrowerCertno);
                    log.info("{}", json);
                    if (1 == json.getInteger("success")) {
                        JSONArray jsonArray = json.getJSONArray("data");
                        if (jsonArray.size() > 0) {
                            for (int i = 0; i < jsonArray.size(); i++) {
                                CertNoDto cerNo = JSONObject.parseObject(JSONObject.toJSONString(jsonArray.get(i)), CertNoDto.class);
                                loanAmount = loanAmount.add(cerNo.getLoanAmount());
                            }
                        }
                    } else {
                        log.info("请求失败:" + json.getString("message"));
                    }
                }
                if (CollectionUtil.isNotEmpty(finCostDetailsList)) {
                    for (FinCostDetails finCostDetails : finCostDetailsList) {
                        loanAmount = loanAmount.add(finCostDetails.getLoanAmt());
                    }
                }
                //累加金额 = 历史金额+本案件金额
                caseBaseInfoDTO.setTotalLoanAmt(loanAmount);
            }
        }
        caseBaseInfoDTO.setCarNature(orderInfoByApplyNo.getCarNature());
        caseBaseInfoDTO.setBusinessType(orderInfoByApplyNo.getBusinessType());
        caseBaseInfoDTO.setAffiliatedWay(orderInfoByApplyNo.getAffiliatedWay());
        caseBaseInfoDTO.setCarPurpose(orderInfoByApplyNo.getCarPurpose());
        if (StringUtil.isNotEmpty(orderInfoByApplyNo.getProductId())) {
            caseBaseInfoDTO.setProductId(Long.valueOf(orderInfoByApplyNo.getProductId()));
        }
        caseBaseInfoDTO.setProductName(orderInfoByApplyNo.getProductName());
        caseBaseInfoDTO.setRemarks(orderInfoByApplyNo.getRemarks());
        return caseBaseInfoDTO;
    }

    /**
     * 案件需要的车辆信息
     *
     * @param applyCarDetails
     * @param orderInfoByApplyNo
     * @return
     */
    @Override
    public ArrayList<CaseCarInfoDto> caseCarInfoList(ApplyCarDetails applyCarDetails, ApplyOrderInfo
            orderInfoByApplyNo) {
        ArrayList<CaseCarInfoDto> caseCarInfoList = new ArrayList<>();
        CaseCarInfoDto caseCarInfoDTO = new CaseCarInfoDto();
        //如果存在挂靠方式，就查询挂靠信息
        if (!orderInfoByApplyNo.getAffiliatedWay().equals(AffiliatedWay.NO.getIndex())) {
            //挂靠信息
            ApplyAffiliatedUnit applyAffiliatedUnit = this.applyAffiliatedUnitService.getOne(Wrappers.<ApplyAffiliatedUnit>query().lambda()
                    .eq(ApplyAffiliatedUnit::getApplyNo, applyCarDetails.getApplyNo()));
            if (ObjectUtil.isNull(applyAffiliatedUnit)) {
                throw new AfsBaseException("车辆挂靠信息不存在");
            }
            caseCarInfoDTO.setIndBusinessUsci(applyAffiliatedUnit.getSocUniCrtCode());
            caseCarInfoDTO.setAffiliatedType(applyAffiliatedUnit.getAffiliatedType());
            caseCarInfoDTO.setAffCompanyId(applyAffiliatedUnit.getAffiliatedId());
            caseCarInfoDTO.setIndBusinessName(applyAffiliatedUnit.getAffiliatedName());
            caseCarInfoDTO.setCooperPlat(applyAffiliatedUnit.getPlatformId());
        }
        caseCarInfoDTO.setId(applyCarDetails.getId());
        caseCarInfoDTO.setApplyNo(applyCarDetails.getApplyNo());
        if (StringUtil.isNotEmpty(applyCarDetails.getFullModelNum())) {
            caseCarInfoDTO.setFullModelNum(applyCarDetails.getFullModelNum());
        }
        if (StringUtil.isNotEmpty(applyCarDetails.getIsMortgage())) {
            caseCarInfoDTO.setIsMortgage(applyCarDetails.getIsMortgage());
        }
        caseCarInfoDTO.setCarVin(applyCarDetails.getCarVin());
        caseCarInfoDTO.setCarManufacturer(applyCarDetails.getCarManufacturer());
        caseCarInfoDTO.setBrandCode(applyCarDetails.getBrandId());
        caseCarInfoDTO.setBrandName(applyCarDetails.getBrandName());
        caseCarInfoDTO.setModelCode(applyCarDetails.getModelId());
        caseCarInfoDTO.setModelName(applyCarDetails.getModelName());
        caseCarInfoDTO.setStyleCode(applyCarDetails.getStyleId());
        caseCarInfoDTO.setStyleName(applyCarDetails.getStyleName());
        caseCarInfoDTO.setGuidePrice(applyCarDetails.getGuidePrice());
        caseCarInfoDTO.setSalePrice(applyCarDetails.getSalePrice());
        caseCarInfoDTO.setFuelType(applyCarDetails.getFuelType());
        caseCarInfoDTO.setEngineNo(applyCarDetails.getEngineNo());
        caseCarInfoDTO.setLicensePlate(applyCarDetails.getLicensePlate());
        caseCarInfoDTO.setCarColor(applyCarDetails.getCarColor());
        caseCarInfoDTO.setCarDisplacement(applyCarDetails.getCarDisplacement());
        caseCarInfoDTO.setCarTransmission(applyCarDetails.getCarTransmission());
        caseCarInfoDTO.setCarFunction(applyCarDetails.getCarFunction());
        caseCarInfoDTO.setLicenseProvince(applyCarDetails.getLicenseProvince());
        caseCarInfoDTO.setLicenseCity(applyCarDetails.getLicenseCity());
        caseCarInfoDTO.setPurchaseProvince(applyCarDetails.getPurchaseProvince());
        caseCarInfoDTO.setPurchaseCity(applyCarDetails.getPurchaseCity());
        caseCarInfoDTO.setTotalPassenger(String.valueOf(applyCarDetails.getTotalPassenger()));
        caseCarInfoDTO.setMileage(applyCarDetails.getMileage());
        caseCarInfoDTO.setCarBelongs(applyCarDetails.getCarBelongs());
        caseCarInfoDTO.setBelongsCertNo(applyCarDetails.getBelongsCertNo());
        caseCarInfoDTO.setBelongsAddress(applyCarDetails.getBelongsAddress());
        caseCarInfoDTO.setSecondSalePrice(applyCarDetails.getSecondSalePrice());
        caseCarInfoDTO.setEvaluatingPrice(applyCarDetails.getEvaluatingPrice());
        caseCarInfoDTO.setVehicleMadeDate(applyCarDetails.getVehicleMadeDate());
        caseCarInfoDTO.setFirstLandingDate(applyCarDetails.getFirstLandingDate());
        caseCarInfoDTO.setCarAppraiser(applyCarDetails.getCarAppraiser());
        caseCarInfoDTO.setCarDealerId(applyCarDetails.getDealerId());
        caseCarInfoDTO.setCarDealerName(applyCarDetails.getDealerName());
        caseCarInfoDTO.setCarDealerPhone(applyCarDetails.getDealerPhone());
        caseCarInfoDTO.setCarDealerProvince(applyCarDetails.getDealerProvince());
        caseCarInfoDTO.setCarDealerCity(applyCarDetails.getDealerCity());
        caseCarInfoDTO.setCarDealerCounty(applyCarDetails.getDealerCounty());
        caseCarInfoDTO.setCarDealerStreet(applyCarDetails.getDealerStreet());
        caseCarInfoDTO.setCarDealerAddress(applyCarDetails.getDealerAddress());
        caseCarInfoDTO.setRegistProvince(applyCarDetails.getRegistProvince());
        caseCarInfoDTO.setRegistCity(applyCarDetails.getRegistCity());
        caseCarInfoDTO.setYearTransNum(applyCarDetails.getYearTransNum());
        caseCarInfoDTO.setTransNums(applyCarDetails.getTransNums());
        caseCarInfoDTO.setInvoiceTime(applyCarDetails.getInvoiceTime());
        caseCarInfoDTO.setIsFirstLicense(applyCarDetails.getIsFirstLicense());
        caseCarInfoDTO.setFirstLicenseProvince(applyCarDetails.getFirstLicenseProvince());
        caseCarInfoDTO.setFirstLicenseCity(applyCarDetails.getFirstLicenseCity());
        caseCarInfoDTO.setIsInternet(applyCarDetails.getIsInternet());
        caseCarInfoDTO.setConfigure(applyCarDetails.getConfigure());
        caseCarInfoDTO.setYearStyle(applyCarDetails.getYearStyle());
        caseCarInfoDTO.setVersion(applyCarDetails.getVersion());
        if (WhetherEnum.YES.getIndex().equals(applyCarDetails.getIsCirTrans())) {
            caseCarInfoDTO.setIsCirTrans(com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum.YES.getCode());
        } else if (WhetherEnum.No.getIndex().equals(applyCarDetails.getIsCirTrans())) {
            caseCarInfoDTO.setIsCirTrans(com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum.NO.getCode());
        } else {
            caseCarInfoDTO.setIsCirTrans(applyCarDetails.getIsCirTrans());
        }
        caseCarInfoDTO.setCarKind(applyCarDetails.getCarKind());
        caseCarInfoDTO.setCarUse(applyCarDetails.getCarUse());
        caseCarInfoDTO.setCarBodyClass(applyCarDetails.getCarBodyClass());
        caseCarInfoDTO.setFirstLicenseAddress(applyCarDetails.getFirstLicenseAddress());
        caseCarInfoList.add(caseCarInfoDTO);
        return caseCarInfoList;
    }


    /**
     * 案件需要的融资信息
     *
     * @param applyCostDetailsList
     * @return
     */
    @Override
    public ArrayList<FinCostDetails> caseCostInfoList(List<FinCostDetails> applyCostDetailsList
    ) {
        ArrayList<FinCostDetails> caseCostInfoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(applyCostDetailsList)) {
            for (FinCostDetails applyCostDetails : applyCostDetailsList) {
                FinCostDetails finCostDetails = new FinCostDetails();
                BeanUtil.copyProperties(applyCostDetails, finCostDetails);
                caseCostInfoList.add(finCostDetails);
            }
        }
        return caseCostInfoList;
    }


    /**
     * 案件需要的融资项目信息
     *
     * @param list
     * @return
     */
    @Override
    public ArrayList<FinFinancingItems> caseFinancingItemList(List<FinFinancingItems> list) {
        ArrayList<FinFinancingItems> caseFinancingItemList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (FinFinancingItems applyFinancingItems : list) {
                FinFinancingItems finFinancingItems = new FinFinancingItems();
                BeanUtil.copyProperties(applyFinancingItems, finFinancingItems);
                caseFinancingItemList.add(finFinancingItems);
            }
        }
        return caseFinancingItemList;
    }

    /**
     * 案件需要的贴息明细
     *
     * @param list
     * @return
     */
    @Override
    public ArrayList<FinDiscountDetails> caseDiscountDetailList(List<FinDiscountDetails> list) {
        ArrayList<FinDiscountDetails> caseDiscountDetailList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (FinDiscountDetails applyDiscountDetails : list) {
                FinDiscountDetails discountDetails = new FinDiscountDetails();
                BeanUtil.copyProperties(applyDiscountDetails, discountDetails);
                caseDiscountDetailList.add(discountDetails);
            }
        }
        return caseDiscountDetailList;
    }

    /**
     * 案件需要的车型详细信息
     *
     * @param applyCarDetails
     * @param vehicleDetail
     * @param tsysVehicleModel
     * @return
     */
    @Override
    public ArrayList<CaseCarStyleDetailDto> caseCarStyleDetailList(ApplyCarDetails applyCarDetails, TsysVehicleDetail vehicleDetail, TsysVehicleModel tsysVehicleModel) {
        ArrayList<CaseCarStyleDetailDto> caseCarStyleDetailList = new ArrayList<>();
        CaseCarStyleDetailDto caseCarStyleDetailDTO = new CaseCarStyleDetailDto();

        if (ObjectUtil.isNotNull(applyCarDetails)) {
            caseCarStyleDetailDTO.setCarId(applyCarDetails.getId());
            caseCarStyleDetailDTO.setDisplacement(applyCarDetails.getCarDisplacement());
            caseCarStyleDetailDTO.setFuelType(applyCarDetails.getFuelType());
            caseCarStyleDetailDTO.setPassengers(applyCarDetails.getTotalPassenger());
        }
        if (ObjectUtil.isNotNull(vehicleDetail)) {
            caseCarStyleDetailDTO.setCarLength(vehicleDetail.getCarLength());
            caseCarStyleDetailDTO.setEmissionStandard(vehicleDetail.getBlowoff());
            caseCarStyleDetailDTO.setTotalQuality(vehicleDetail.getWight());
            caseCarStyleDetailDTO.setIsGreen(vehicleDetail.getIsGreen());
            caseCarStyleDetailDTO.setCarType(vehicleDetail.getCarType());
            caseCarStyleDetailDTO.setCarTypeDetail(vehicleDetail.getCarTypeDetail());
            caseCarStyleDetailDTO.setCarModelId(vehicleDetail.getModelId());// add by sijun.yu 2020-10-14
        }
        if (ObjectUtil.isNotNull(tsysVehicleModel)) {
            caseCarStyleDetailDTO.setType(tsysVehicleModel.getType());
        }
        caseCarStyleDetailList.add(caseCarStyleDetailDTO);
        return caseCarStyleDetailList;
    }

    /**
     * 影像件
     *
     * @param attachmentFileList
     * @return
     */
    @Override
    public ArrayList<ComAttachmentFileDto> comAttachmentFile(List<ComAttachmentFile> attachmentFileList) {
        ArrayList<ComAttachmentFileDto> comAttachmentFileList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(attachmentFileList)) {
            for (ComAttachmentFile comAttachmentFile : attachmentFileList) {
                ComAttachmentFileDto comAttachmentFileDto = new ComAttachmentFileDto();
                BeanUtil.copyProperties(comAttachmentFile, comAttachmentFileDto);
                comAttachmentFileList.add(comAttachmentFileDto);
            }
        }
        return comAttachmentFileList;
    }

    /**
     * 租金调整信息
     *
     * @param rentAdjustDetailsList
     * @return
     */
    @Override
    public ArrayList<FinRentAdjustDetails> applyRentAdjustDetails
    (List<FinRentAdjustDetails> rentAdjustDetailsList) {
        ArrayList<FinRentAdjustDetails> adjustDetailsDtoArrayList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(rentAdjustDetailsList)) {
            for (FinRentAdjustDetails applyRentAdjustDetails : rentAdjustDetailsList) {
                FinRentAdjustDetails rentAdjustDetails = new FinRentAdjustDetails();
                if (ObjectUtil.isNotNull(applyRentAdjustDetails)) {
                    BeanUtil.copyProperties(applyRentAdjustDetails, rentAdjustDetails);
                }
                adjustDetailsDtoArrayList.add(rentAdjustDetails);
            }
        }
        return adjustDetailsDtoArrayList;
    }

    /**
     * MQ加急
     *
     * @param applyNo
     * @return
     * @throws ParseException
     */
    @Override
    public AfsTransEntity<UrgentInfoSubmitInfo> returnEmergencyMessage(String applyNo) throws ParseException {
        AfsTransEntity<UrgentInfoSubmitInfo> afsTransEntity = new AfsTransEntity();
        UrgentInfoSubmitInfo urgentInfoSubmitInfo = new UrgentInfoSubmitInfo();
        CaseUrgentDto caseUrgentDto = new CaseUrgentDto();
        caseUrgentDto.setApplyNo(applyNo);
        urgentInfoSubmitInfo.setCaseUrgent(caseUrgentDto);
        afsTransEntity.setData(urgentInfoSubmitInfo);
        afsTransEntity.setTransCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_TURN_URGENT);
        return afsTransEntity;
    }

    /**
     * 资产变更
     *
     * @param applyNo
     * @return
     * @throws ParseException
     */
    @Override
    public AfsTransEntity<ApproveSpecialSubmitInfo> returnAssertChangeMessage(String applyNo, List<ComAttachmentFile> fileList) throws ParseException {

        // 判断是否可以进行资产变更
        AfsTransEntity<ApproveSpecialSubmitInfo> afsTransEntity = new AfsTransEntity<>();
        ApproveSpecialSubmitInfo approveSpecialSubmitInfo = new ApproveSpecialSubmitInfo();
        ApproveInformDto approveInformDto = new ApproveInformDto();
        approveInformDto.setApplyNo(applyNo);
        ApplyModifyHistory modifyHistory = applyModifyHistoryService.getModifyHistoryByApplyNo(applyNo);
        JSONObject jsonObject = new JSONObject();
        //变更前
        String beforeParameter = modifyHistory.getBeforeParameter();
        //变更后
        String afterParameter = modifyHistory.getAfterParameter();
        Assert.isTrue(StringUtil.isNotEmpty(afterParameter), "请保存资产变更信息之后再提交");
        //变更后object
        String bodyContent = modifyHistory.getBodyContent();
        jsonObject.put("bodyContent", bodyContent);
        jsonObject.put("afterParameter", afterParameter);
        jsonObject.put("beforeParameter", beforeParameter);
        approveSpecialSubmitInfo.setApplyNo(applyNo);
        approveSpecialSubmitInfo.setChangeDataJson(jsonObject);
        //查询操作表信息
        List<ApplyOprRecord> oprRecordList = applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda().eq(ApplyOprRecord::getApplyNo, applyNo)
                .eq(ApplyOprRecord::getApplyType, OrderOprType.ASSERTCHANGE).orderByDesc(ApplyOprRecord::getCreateTime));
        //存在资产变更操作记录
        if (CollectionUtil.isNotEmpty(oprRecordList)) {
            ApplyOprRecord applyOprRecord = oprRecordList.get(0);
            //未审批结束
            if (applyOprRecord.getApproveDate() == null && StringUtil.isNotEmpty(applyOprRecord.getProcessId())) {
                //查询资产变更的退回的审批记录信息
                List<WorkflowRecordDetails> detailsList = applyRecordDetailsService.list(Wrappers.<WorkflowRecordDetails>query().lambda()
                        .eq(WorkflowRecordDetails::getBusinessNo, applyOprRecord.getId()).eq(WorkflowRecordDetails::getApproveResult, AProveBusinessTypeEnum.BACK.getCode()).orderByDesc(WorkflowRecordDetails::getCreateTime));
                if (CollectionUtil.isNotEmpty(detailsList)) {
                    //资产变更-修订暂停->修订回复-流程id
                    approveInformDto.setStageId(applyOprRecord.getProcessId());
                    approveSpecialSubmitInfo.setApproveInformDto(approveInformDto);
                    //更新资产变更状态为修订回复
                    applyOprRecord.setApplyStatus(AssetChangeEnums.REVISIONREPLY.getCode());
                    this.applyOprRecordService.updateById(applyOprRecord);
                }
                //资产变更退回留言
                log.info("{}，资产变更-修订暂停->修订回复", applyNo);
            } else {
                approveInformDto.setStageId("");
                approveSpecialSubmitInfo.setApproveInformDto(approveInformDto);
            }
            if (ObjectUtil.isNull(modifyHistory.getVersion())) {
                Integer version = applyModifyHistoryService.getMaxVersion(applyNo);
                if (ObjectUtil.isNull(version)) {
                    modifyHistory.setVersion(ApplyConstants.ONE_INT);
                } else {
                    modifyHistory.setVersion(version + ApplyConstants.ONE_INT);
                }
                modifyHistory.setOprId(applyOprRecord.getId());
                applyModifyHistoryService.updateById(modifyHistory);
            }
        }
        // 影像资料
        if (CollectionUtil.isNotEmpty(fileList)) {
            ArrayList<ComAttachmentFileDto> comAttachmentFileListDto = new ArrayList<ComAttachmentFileDto>();
            fileList.forEach(x -> {
                ComAttachmentFileDto dto = new ComAttachmentFileDto();
                BeanUtil.copyProperties(x, dto);
                dto.setBusiNo(applyNo);
                dto.setBelongNo(applyNo);
                dto.setHistoryVersion(modifyHistory.getVersion().toString());
                comAttachmentFileListDto.add(dto);
            });
            approveSpecialSubmitInfo.setComAttachmentFileListDto(comAttachmentFileListDto);
        }
        afsTransEntity.setData(approveSpecialSubmitInfo);
        afsTransEntity.setTransCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_ASSETS_RECONSIDER);
        return afsTransEntity;
    }

    /**
     * 申请复议
     *
     * @param applyNo
     * @return
     * @throws ParseException
     */
    @Override
    public AfsTransEntity<ReconsiderationDto> returnSaveReconsiderMessage(String applyNo, List<ComAttachmentFile> fileList) throws ParseException {
        AfsTransEntity<ReconsiderationDto> afsTransEntity = new AfsTransEntity<>();
        ReconsiderationDto reconsiderationDto = new ReconsiderationDto();
        ApplyOrderInfo orderInfo = this.orderInfoService.getOrderInfoByApplyNo(applyNo);
        ApplyOprRecord applyOprRecord = new ApplyOprRecord();
        if (ObjectUtil.isNotNull(orderInfo)) {
            //订单不是已拒绝的
            if (!ApplyConstants.APPLY_STATUS_REFUSE.equals(orderInfo.getApplyStatus())) {
                throw new AfsBaseException("编号:" + applyNo + "不是已拒绝订单,不可进行复议操作");
            }
            //订单操作表数据
            List<ApplyOprRecord> list = this.applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda()
                    .eq(StringUtil.isNotEmpty(applyNo), ApplyOprRecord::getApplyNo, applyNo).eq(ApplyOprRecord::getApplyType, OrderOprType.RECONSIDER));
            if (CollectionUtil.isNotEmpty(list)) {
                applyOprRecord = list.get(list.size() - 1);
            }
            // 影像资料
            if (CollectionUtil.isNotEmpty(fileList)) {
                ArrayList<ComAttachmentFileDto> comAttachmentFileListDto = new ArrayList<ComAttachmentFileDto>();
                fileList.forEach(x -> {
                    ComAttachmentFileDto dto = new ComAttachmentFileDto();
                    BeanUtil.copyProperties(x, dto);
                    comAttachmentFileListDto.add(dto);
                });
                reconsiderationDto.setComAttachmentFileListDto(comAttachmentFileListDto);
            }
            reconsiderationDto.setApplyNo(applyOprRecord.getApplyNo());
            reconsiderationDto.setReconReason(applyOprRecord.getApplyReason());
            afsTransEntity.setData(reconsiderationDto);
            afsTransEntity.setTransCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_ASSETS_RECONSIDERATION);
        } else {
            throw new AfsBaseException("编号:" + applyNo + "未查询到匹配订单");
        }
        return afsTransEntity;
    }

    /**
     * 保存复议信息
     *
     * @param condition
     * @return
     */
    @Override
    public void saveReconsideration(CaseSubmitInfoCondition condition) throws ParseException {
        //查询复议次数
        int count = Integer.parseInt(tSysParamConfigService.getParamValue("orderReconsider", "number", "1"));
        //查询复议数据
        List<ApplyOprRecord> list = this.applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda()
                .eq(StringUtil.isNotEmpty(condition.getApplyNo()), ApplyOprRecord::getApplyNo, condition.getApplyNo())
                .eq(ApplyOprRecord::getApplyType, OrderOprType.RECONSIDER));
        //首先查询复议留言，判断是否是反欺诈拒绝
        ApplyRemindDetails remindDetails = applyRemindDetailsService.getOne(Wrappers.<ApplyRemindDetails>query().lambda().eq(ApplyRemindDetails::getApplyNo, condition.getApplyNo())
                .eq(ApplyRemindDetails::getBusinessType, String.valueOf(OrderOprType.RECONSIDER)).eq(ApplyRemindDetails::getRemindType, AProveBusinessTypeEnum.SEND_BACK_TO_DEALER.getCode()));
        if (ObjectUtil.isNotNull(remindDetails)) {
            throw new AfsBaseException("该订单触发过玄武反欺诈拒绝，不允许复议");
        }
        //复议操作不为空
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(applyOprRecord -> {
                //审批时间为空，还未获得复议审批结果，则在复议流程中，不可再次复议
                if (applyOprRecord.getApproveDate() == null) {
                    throw new AfsBaseException("订单复议中");
                } else if (list.size() >= count) {
                    throw new AfsBaseException("复议次数不可超过" + count + "次");
                }
            });
        }
        //查询客户信息
        ApplyCustBaseInfo custBaseInfo = this.applyCustBaseInfoService.getCustBaseInfo(condition.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);
        //查询订单信息
        ApplyOrderInfo orderInfoByApplyNo = this.orderInfoService.getOrderInfoByApplyNo(condition.getApplyNo());
        //查询复议信息，
        //保存复议操作信息
        ApplyOprRecord oprRecord = new ApplyOprRecord();
        oprRecord.setApplyNo(condition.getApplyNo());
        oprRecord.setCertNo(custBaseInfo.getCertNo());
        oprRecord.setCustName(orderInfoByApplyNo.getCustName());
        oprRecord.setApplyStatus(FormalReviewEnums.REFUSALREVIEW.getCode());
        oprRecord.setApplyType(OrderOprType.RECONSIDER);
        oprRecord.setApplyReason(condition.getReconsiderReason());
        oprRecord.setCreateTime(new Date());
        oprRecord.setCreateBy(orderInfoByApplyNo.getCreateBy());
        applyOprRecordService.save(oprRecord);
    }

    /**
     * <p>description：</p>
     * 撤回申请组装DTO
     *
     * @throws ParseException
     * @author ma_xueyu
     * @date 2020年8月31日
     */
    @Override
    public AfsTransEntity<CallBackApplyDto> returnCallBackMessage(String applyNo) throws ParseException {
        AfsTransEntity<CallBackApplyDto> afsTransEntity = new AfsTransEntity<>();
        ApplyOprRecord applyOprRecord = this.applyOprRecordService.getOne(Wrappers.<ApplyOprRecord>query()
                .lambda().eq(StringUtil.isNotEmpty(applyNo), ApplyOprRecord::getApplyNo, applyNo)
                .eq(ApplyOprRecord::getApplyType, OrderOprType.BACK));
        CallBackApplyDto callBackApplyDto = new CallBackApplyDto();
        callBackApplyDto.setApplyNo(applyNo);
        callBackApplyDto.setApplyReporter(SecurityUtils.getUser().getUserRealName());
        callBackApplyDto.setCallBackReason(applyOprRecord.getApplyReason());
        ApplyChannelInfo applyChannelInfo = applyChannelInfoService.getOne(Wrappers.<ApplyChannelInfo>query().lambda()
                .eq(ApplyChannelInfo::getApplyNo, applyNo));
        callBackApplyDto.setChannelName(applyChannelInfo.getChannelName());
        afsTransEntity.setData(callBackApplyDto);
        afsTransEntity.setTransCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_CALL_BACK);
        return afsTransEntity;
    }


    /**
     * 数据校验
     *
     * @param applyNo 申请编号
     */
    @Override
    public CaseSbmitInfoDto checkData(String applyNo) {
        CaseSbmitInfoDto caseSbmitInfoDto = new CaseSbmitInfoDto();
        ApplyOrderInfo orderInfoByApplyNo = this.applyOrderInfoService.getOrderInfoByApplyNo(applyNo);
        caseSbmitInfoDto.setApplyOrderInfo(orderInfoByApplyNo);
        //车辆信息
        ApplyCarDetails applyCarDetails = applyCarDetailsService.getOne(Wrappers.<ApplyCarDetails>query().lambda()
                .eq(ApplyCarDetails::getApplyNo, applyNo));
        if (ObjectUtil.isNull(applyCarDetails)) {
            throw new AfsBaseException("请先保存资产信息");
        }
        caseSbmitInfoDto.setApplyCarDetails(applyCarDetails);
        //根据申请编号查询客户基础信息
        List<ApplyCustBaseInfo> applyCustBaseInfoList = this.applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, applyNo));
        if (CollectionUtil.isEmpty(applyCustBaseInfoList)) {
            throw new AfsBaseException("请先保存客户信息");
        }
        //客户证件到期日校验
        applyCustBaseInfoList.forEach(applyCustBaseInfo -> {
            if (applyCustBaseInfo.getCertEndDate() != null) {
                //证件到期日不可小于当前时间
                if (applyCustBaseInfo.getCertEndDate().compareTo(new Date()) < 0) {
                    if (ApplyConstants.PRINCIPAL_BORROWER.equals(applyCustBaseInfo.getCustRole())) {
                        throw new AfsBaseException("主借人证件到期日不可小于当前时间");
                    } else if (ApplyConstants.COMMON_BORROWER.equals(applyCustBaseInfo.getCustRole())) {
                        throw new AfsBaseException("共借人证件到期日不可小于当前时间");
                    } else if (ApplyConstants.GUARANTOR.equals(applyCustBaseInfo.getCustRole())) {
                        throw new AfsBaseException("担保人证件到期日不可小于当前时间");
                    }
                }
            }
        });
        caseSbmitInfoDto.setApplyCustBaseInfoList(applyCustBaseInfoList);
        //获取地址信息,根据applyNo
        List<ApplyCustAddressDetails> applyCustAddressDetailsList = this.applyCustAddressService.list(Wrappers.<ApplyCustAddressDetails>query().lambda()
                .eq(ApplyCustAddressDetails::getApplyNo, applyNo));
        if (CollectionUtil.isEmpty(applyCustAddressDetailsList)) {
            throw new AfsBaseException("请先保存地址信息");
        }
        caseSbmitInfoDto.setAddressDetailsList(applyCustAddressDetailsList);
        //获取客户联系人信息list
        List<ApplyCustContacts> applyCustContactsList = applyCustContactsService.list(Wrappers.<ApplyCustContacts>query().lambda()
                .eq(ApplyCustContacts::getApplyNo, applyNo));
        if (CollectionUtil.isEmpty(applyCustContactsList)) {
            throw new AfsBaseException("请先保存客户联系人信息");
        }
        caseSbmitInfoDto.setApplyCustContactsList(applyCustContactsList);
        //融资信息
        List<FinCostDetails> applyCostDetailsList = this.applyCostDetailsService.list(Wrappers.<FinCostDetails>query().lambda()
                .eq(FinCostDetails::getApplyNo, applyNo));
        if (CollectionUtil.isEmpty(applyCostDetailsList)) {
            throw new AfsBaseException("请先保存");
        }
        //身份验重
        ApplyCustBaseInfo applyCustBaseInfo = applyCustBaseInfoService.getCustBaseInfo(applyNo, ApplyConstants.PRINCIPAL_BORROWER);
        ApplyCustBaseInfo applyCustBaseInfoCommon = applyCustBaseInfoService.getCustBaseInfo(applyNo, ApplyConstants.COMMON_BORROWER);
        ApplyCustBaseInfo applyCustBaseInfoGuarntor = applyCustBaseInfoService.getCustBaseInfo(applyNo, ApplyConstants.GUARANTOR);
        CertNoDto certNoDto = new CertNoDto();
        if (applyCustBaseInfo != null) {
            certNoDto.setBorrowerCertno(applyCustBaseInfo.getCertNo());
        } else {
            certNoDto.setBorrowerCertno("none");
        }
        if (applyCustBaseInfoCommon != null) {
            certNoDto.setCoborrowerCertno(applyCustBaseInfoCommon.getCertNo());
        } else {
            certNoDto.setCoborrowerCertno("none");
        }
        if (applyCustBaseInfoGuarntor != null) {
            certNoDto.setGuarantorCertno(applyCustBaseInfoGuarntor.getCertNo());
        } else {
            certNoDto.setGuarantorCertno("none");
        }
        //聚合接口调用
        List<CertNoCheckDto> certNoCheckDtoList = applyOrderInfoService.getCertNoCheckInfo(certNoDto);
        if (certNoCheckDtoList != null) {
            if (certNoCheckDtoList.size() > 0) {
                //主借人数量
                int countMain = 0;
                //共借人数量
                int countCommon = 0;
                //担保人数量
                int countGuarntor = 0;
                for (CertNoCheckDto certNoCheckDto : certNoCheckDtoList) {
                    if (certNoCheckDto.getCertNo().equals(applyCustBaseInfo == null ? "" : applyCustBaseInfo.getCertNo()) && !certNoCheckDto.getApplicationNo().equals(applyNo)) {
                        countMain += 1;
                    }
                    if (certNoCheckDto.getCertNo().equals(applyCustBaseInfoCommon == null ? "" : applyCustBaseInfoCommon.getCertNo()) && !certNoCheckDto.getApplicationNo().equals(applyNo)) {
                        countCommon += 1;
                    }
                    if (certNoCheckDto.getCertNo().equals(applyCustBaseInfoGuarntor == null ? "" : applyCustBaseInfoGuarntor.getCertNo()) && !certNoCheckDto.getApplicationNo().equals(applyNo)) {
                        countGuarntor += 1;
                    }
                }
                if (countMain >= 2) {
                    throw new AfsBaseException("主借人已达到我司最高申请数量");
                } else if (countCommon >= 2) {
                    throw new AfsBaseException("共借人已达到我司最高申请数量");
                } else if (countGuarntor >= 2) {
                    throw new AfsBaseException("保证人已达到我司最高申请数量");
                }
            }
        }
        //是否进行过电子授权
        if (applyCustBaseInfo != null) {
            if (applyCustBaseInfo.getSignResult() == null) {
                throw new AfsBaseException("请先电子授权");
            } else if (applyCustBaseInfo.getSignResult().equals(ApplyConstants.NO) && applyCustBaseInfo.getSignFailNumber() <= 3) {
                throw new AfsBaseException("电子授权未通过，请重试！");
            }
        } else {
            throw new AfsBaseException("请先保存主借人信息");
        }
        //网约车额度校验
        ApplyAffiliatedUnit applyAffiliatedUnit = applyAffiliatedUnitService.getAffiliatedUnitByApplyNo(applyNo);
        if (applyAffiliatedUnit != null) {
            if (AffiliatedWayEnum.NETWORK_CAR_AFFILIATED.equals(applyAffiliatedUnit.getAffiliatedType())) {
                BigDecimal money = BigDecimal.ZERO;
                List<FinCostDetails> costDetailsList = applyCostDetailsService.getCostDetailsList(applyNo);
                if (costDetailsList.size() > 0) {
                    for (FinCostDetails costDetails : costDetailsList) {
                        money = money.add(costDetails.getLoanAmt() == null ? BigDecimal.ZERO : costDetails.getLoanAmt());
                    }
                }
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("clientId", config.getCaseClientId());
                headers.put("clientSecret", config.getCaseClientSecret());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", applyAffiliatedUnit.getAffiliatedId());
                ChannelAffiliatedUnitsDto channelAffiliatedUnitsDto = apply2ChannelFeign.getAffiliatedById(jsonObject, headers);
                if (channelAffiliatedUnitsDto != null) {
                    AffiliatedCheckDto affiliatedCheckDto = applyOrderInfoService.getAffiliatedCheckInfo(applyAffiliatedUnit.getSocUniCrtCode(), channelAffiliatedUnitsDto.getLimitValue());
                    if (affiliatedCheckDto.getIsOverCritical()) {
                        int surplus = affiliatedCheckDto.getTotalRepaidMoney().intValue() - affiliatedCheckDto.getTotalLoanMoney().intValue();
                        if (surplus < money.intValue()) {
                            throw new AfsBaseException("该网约车贷款金额不足");
                        }
                    } else {
                        if ((channelAffiliatedUnitsDto.getLimitValue().intValue() - affiliatedCheckDto.getUnFiledNumber().intValue() - affiliatedCheckDto.getWaitingApproval().intValue()) <= 0) {
                            throw new AfsBaseException("该网约车申请数量已达限额值");
                        }
                    }
                } else {
                    throw new AfsBaseException("获取网约车挂靠信息失败");
                }
            }
        }
        //二手车VIN查重
        if (BusinessTypeEnum.OLD_CAR.getCode().equals(orderInfoByApplyNo.getBusinessType())) {
            List<UsedVinInfoDto> list = applyOrderInfoService.getUsedVinInfo(applyCarDetails.getCarVin());
            if (list != null) {
                if (list.size() > 0) {
                    for (UsedVinInfoDto usedVinInfoDto : list) {
                        if (!usedVinInfoDto.getApplicationNo().equals(applyNo)) {
                            throw new AfsBaseException("该VIN号已被使用，请重新填写");
                        }
                    }
                }
            }
            String value = tSysParamConfigService.getParamValue("vinVersion", "number", "");
            if (value.equals(ApplyConstants.YES)) {
                ApplyCarDetails carDetailsByApplyNo = applyCarDetailsService.getCarDetailsByApplyNo(applyNo);
                CarInfoDto carInfo = new CarInfoDto();
                carInfo.setVin(carDetailsByApplyNo.getCarVin());
                carInfo.setStartDate((new Date()).getTime());
                carInfo.setEndDate((new Date()).getTime());
                JSONObject json = applyCarDetailsService.getValuationReport(carInfo);
                if (0 == json.getInteger("code")) {
                    JSONArray jsonArray = json.getJSONArray("data");
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    carDetailsByApplyNo.setVersion(jsonObject.getString("version"));
                    JSONObject jsonInfo = jsonObject.getJSONObject("content");
                    carDetailsByApplyNo.setEvaluatingPrice(jsonInfo.getBigDecimal("appraiseprice"));
                    applyCarDetailsService.updateById(carDetailsByApplyNo);
                } else if (500 == json.getInteger("code")) {
                    throw new AfsBaseException(json.getString("msg"));
                }
            }
        }
        caseSbmitInfoDto.setFinCostDetailsList(applyCostDetailsList);
        //影像件信息
        List<ComAttachmentFile> comAttachmentFileList = this.comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                .eq(StringUtil.isNotEmpty(applyNo), ComAttachmentFile::getBusiNo, applyNo));
        caseSbmitInfoDto.setAttachmentFileList(comAttachmentFileList);
        //融资项目信息
        List<FinFinancingItems> finFinancingItemsList = this.applyFinancingItemsService.list(Wrappers.<FinFinancingItems>query().lambda()
                .eq(FinFinancingItems::getApplyNo, applyNo));
        caseSbmitInfoDto.setFinancingItemsList(finFinancingItemsList);
        List<FinDiscountDetails> applyDiscountDetailsList = this.applyDiscountDetailsService.list(Wrappers.<FinDiscountDetails>query().lambda()
                .eq(FinDiscountDetails::getApplyNo, applyNo));
        caseSbmitInfoDto.setDiscountDetailsList(applyDiscountDetailsList);
        //查询款式信息
        TsysVehicleDetail vehicleDetail = this.tsysVehicleDetailService.getOne(Wrappers.<TsysVehicleDetail>query().lambda()
                .eq(TsysVehicleDetail::getModelCode, applyCarDetails.getModelId()).eq(TsysVehicleDetail::getName, applyCarDetails.getStyleName()));
        caseSbmitInfoDto.setTsysVehicleDetail(vehicleDetail);
        //查询车型信息
        TsysVehicleModel tsysVehicleModel = this.tsysVehicleModelService.getOne(Wrappers.<TsysVehicleModel>query().lambda()
                .eq(TsysVehicleModel::getBrandCode, applyCarDetails.getBrandId()).eq(TsysVehicleModel::getFullName, applyCarDetails.getModelName()));
        caseSbmitInfoDto.setTsysVehicleModel(tsysVehicleModel);
        //查询渠道信息
        ApplyChannelInfo channelInfoByApplyNo = this.applyChannelInfoService.getChannelInfoByApplyNo(applyNo);
        caseSbmitInfoDto.setApplyChannelInfo(channelInfoByApplyNo);
        //查询租金调整信息
        List<FinRentAdjustDetails> applyRentAdjustDetailsList = this.applyRentAdjustDetailsService.getRentAdjustDetails(applyNo);
        caseSbmitInfoDto.setRentAdjustDetailsList(applyRentAdjustDetailsList);
        return caseSbmitInfoDto;
    }
    public AfsTransEntity<RepealDealDto> applyCancel(ContractCancelCondition condition) {
        AfsTransEntity<RepealDealDto> transEntity = new AfsTransEntity<>();
        //合同取消
        RepealDealDto repealDealDto = new RepealDealDto();
        repealDealDto.setApplyNo(condition.getApplyNo());
        repealDealDto.setBusinessStateIn(ApplyConstants.APPLY_STATUS_REVOKE);
        log.info("*******进件撤销******" + repealDealDto);
        transEntity.setTransCode(MqTransCode.AFS_POS_APPLY_CASE_CTM_APPROVE_CASE_REPEAL_SEND);
        transEntity.setData(repealDealDto);
        return transEntity;
    }

}